<template>
  <div class="page-wrapper">
    <!-- 水印容器 -->
    <div class="watermarks">
      <div v-for="index in 40" :key="index" class="watermark" :style="getWatermarkStyle(index)">ZBT</div>
    </div>

    <div class="top-bar">
      <button class="back-btn" @click="goBack">返回</button>
      <button class="export-btn" @click="exportToExcel">导出为Excel</button>
      <button class="export-btn" @click="exportToPdf">导出为PDF</button>
    </div>

    <div class="profile-container">
      <h2 class="profile-title">{{ user.name }}的体测档案</h2>

      <div class="profile-header">
        <img v-if="user.profilePicture" :src="user.profilePicture" alt="个人头像" class="profile-image" />
      </div>

      <!-- 基础信息 -->
      <div class="profile-section">
        <h3>基础信息</h3>
        <div class="profile-grid">
          <p><strong>姓名:</strong> {{ user.name }}</p>
          <p><strong>性别:</strong> {{ user.gender === 1 ? '男' : '女' }}</p>
          <p><strong>身份证号:</strong> {{ user.idCard }}</p>
          <p><strong>学号:</strong> {{ user.studentId }}</p>
          <p><strong>学院:</strong> {{ user.college }}</p>
          <p><strong>年级编号:</strong> {{ user.gradeId }}</p>
          <p><strong>班级编号:</strong> {{ user.classId }}</p>
          <p><strong>班级名称:</strong> {{ user.className }}</p>
          <p><strong>出生日期:</strong> {{ user.birthDate }}</p>
          <p><strong>民族:</strong> {{ user.nationality }}</p>
          <p><strong>籍贯:</strong> {{ user.nativePlace }}</p>
          <p><strong>家庭住址:</strong> {{ user.homeAddress }}</p>
        </div>
      </div>

      <!-- 体能训练情况 -->
      <div class="profile-section">
        <h3>体测情况</h3>
        <span @click="changePhysicalTable()">
          {{ isPhysicalTable ? '收起▼' : '点击展开▶' }}
        </span>
        <div v-if="isPhysicalTable">
          <div v-if="user.militaryInterestGroups.length > 0" class="table-container">
            <table class="compare-table">
              <thead>
                <tr>
                  <th colspan="1" rowspan="2">项目</th>
                  <th :colspan="user.militaryInterestGroups.length * 2" class="main-header">体能测试成绩</th>
                </tr>
                <tr>
                  <!-- 年份标题 -->
                  <template v-for="group in user.militaryInterestGroups" :key="group.id">
                    <th colspan="2">{{ group.name }}</th>
                  </template>
                </tr>
                <tr>
                  <th>测试项</th>
                  <!-- 成绩和分数的列标题 -->
                  <template v-for="_ in user.militaryInterestGroups" :key="_">
                    <th>成绩</th>
                    <th>分数</th>
                  </template>
                </tr>
              </thead>
              <tbody>
                <!-- 遍历所有测试项目 -->
                <template v-for="item in physicalItems" :key="item">
                  <tr>
                    <td class="item-name">{{ item }}</td>
                    <!-- 遍历每个年份，查找对应测试项的数据 -->
                    <template v-for="group in user.militaryInterestGroups" :key="group.id">
                      <td>
                        {{ getScore(group.physicalTestScores, item) || '-' }}
                      </td>
                      <td>
                        {{ getPoints(group.physicalTestScores, item) || '-' }}
                      </td>
                    </template>
                  </tr>
                </template>
                <!-- 考核结果行 -->
                <tr class="summary-row">
                  <td>考核结果</td>
                  <template v-for="group in user.militaryInterestGroups" :key="group.id">
                    <td colspan="2" class="result-cell">{{ group.examResult }}<span>/{{ group.totalScore }}</span></td>
                  </template>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else>
            暂无体测数据
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getStudentDetailInfo } from '@/api/allSchool/allSchool';

const isPhysicalTable = ref(true);

const changePhysicalTable = () => {
  isPhysicalTable.value = !isPhysicalTable.value;
};

const user = ref({
  name: '',
  gender: 0,
  idCard: '',
  studentId: '',
  college: '',
  profilePicture: '',
  birthDate: '',
  nationality: '',
  nativePlace: '',
  homeAddress: '',
  gradeId: '',
  classId: '',
  className: '',
  militaryInterestGroups: [],
});

const studentId = useRoute().query.studentId;


function initData() {
  getStudentDetailInfo(studentId).then(response => {
    const data = response.data;
    // 使用 Vite 支持的方式动态加载图片
    const isMale = data.gender === 1;
    const avatarUrl = isMale
      ? new URL('@/assets/images/manAvatar.png', import.meta.url).href
      : new URL('@/assets/images/womanAvatar.png', import.meta.url).href;

    user.value = {
      name: data.name || '',
      gender: data.gender || 0,
      idCard: data.idNumber || '',
      studentId: data.studentId || '',
      college: data.collegeName || '',
      profilePicture: avatarUrl,
      birthDate: data.birthDate || '',
      nationality: getNationalityName(data.ethnicCode) || '',
      nativePlace: data.sourceRegion || '',
      homeAddress: data.homeAddress || '',
      gradeId: data.gradeId || '',
      classId: data.classId || '',
      className: data.className || '',
      militaryInterestGroups: (data.physicalTestVOList || []).map(testData => ({
        id: testData.testYear,
        name: `${testData.testYear}年度`,
        examResult: testData.testGrade || '-',
        totalScore: testData.totalScore || '-',
        physicalTestScores: [
          { name: '身高', score: testData.height ? `${testData.height}cm` : '-' },
          { name: '体重', score: testData.weight ? `${testData.weight}kg` : '-' },
          { name: 'BMI', score: testData.bmi || '-', points: testData.heightWeightScore || '-' },
          { name: '视力', score: testData.leftEyeVision && testData.rightEyeVision ? `${testData.leftEyeVision}/${testData.rightEyeVision}` : '-' },
          { name: '肺活量', score: testData.lungCapacity ? `${testData.lungCapacity}ml` : '-', points: testData.lungCapacityScore || '-' },
          { name: '立定跳远', score: testData.standingJump ? `${testData.standingJump}cm` : '-', points: testData.standingJumpScore || '-' },
          { name: '座位体前屈', score: testData.sitReach ? `${testData.sitReach}cm` : '-', points: testData.sitReachScore || '-' },
          { name: '50米跑', score: testData.fiftyMeter ? `${testData.fiftyMeter}秒` : '-', points: testData.fiftyMeterScore || '-' },
        ].concat(
          data.gender === 1 ? [
            { name: '1000米跑', score: testData.oneThousandMeter || '-', points: testData.enduranceRunScore || '-' },
            { name: '引体向上', score: testData.pullUps ? `${testData.pullUps}个` : '-', points: testData.strengthScore || '-' },
          ] : [
            { name: '800米跑', score: testData.eightHundredMeter || '-', points: testData.enduranceRunScore || '-' },
            { name: '仰卧起坐', score: testData.sitUps ? `${testData.sitUps}个/分钟` : '-', points: testData.strengthScore || '-' },
          ]
        ),
      })),
    };
  }).catch(error => {
    console.error("请求失败:", error);
    ElMessage.error('请求失败！');
  });
}

function getNationalityName(code: number | string): string {
  // 统一转为数字类型
  const numericCode = parseInt(String(code), 10);

  const nationalityMap: Record<number, string> = {
    1: '汉族',
    2: '满族',
    3: '回族',
    4: '苗族',
    5: '壮族',
    6: '藏族',
    7: '蒙古族',
    8: '维吾尔族',
    9: '彝族',
    10: '布依族',
    11: '朝鲜族',
    12: '侗族',
    13: '瑶族',
    14: '白族',
    15: '土家族',
    16: '哈萨克族',
    17: '哈尼族',
    18: '黎族',
    19: '傣族',
    20: '畲族',
    21: '傈僳族',
    22: '仡佬族',
    23: '东乡族',
    24: '高山族',
    25: '拉祜族',
    26: '水族',
    27: '佤族',
    28: '纳西族',
    29: '羌族',
    30: '土族',
    31: '仫佬族',
    32: '锡伯族',
    33: '柯尔克孜族',
    34: '达斡尔族',
    35: '景颇族',
    36: '毛南族',
    37: '撒拉族',
    38: '塔吉克族',
    39: '阿昌族',
    40: '普米族',
    41: '鄂温克族',
    42: '怒族',
    43: '京族',
    44: '基诺族',
    45: '德昂族',
    46: '保安族',
    47: '俄罗斯族',
    48: '裕固族',
    49: '乌兹别克族',
    50: '门巴族',
    51: '鄂伦春族',
    52: '独龙族',
    53: '塔塔尔族',
    54: '赫哲族',
    55: '珞巴族',
    56: '未识别民族',
    99: '其他'
  };

  return nationalityMap[numericCode] || '其他';
}


onMounted(() => {
  initData();
});

const physicalItems = computed(() => {
  if (user.value.gender === 1) {
    return [
      '身高', '体重', 'BMI', '视力', '肺活量', '立定跳远', '座位体前屈', '50米跑', '1000米跑', '引体向上',
    ];
  } else {
    return [
      '身高', '体重', 'BMI', '视力', '肺活量', '立定跳远', '座位体前屈', '50米跑', '800米跑', '仰卧起坐',
    ];
  }
});

const getScore = (scores, item) => {
  const found = scores.find(s => s.name === item);
  return found ? found.score : '-';
};

const getPoints = (scores, item) => {
  const found = scores.find(s => s.name === item);
  return found && found.points !== undefined ? found.points : '-';
};

const goBack = () => {
  window.history.back();
};

const exportToExcel = () => {
  ElMessage.info("还在开发中！");
};

const exportToPdf = () => {
  ElMessage.info("还在开发中！");
};

const getWatermarkStyle = (index) => {
  const top = Math.random() * 100;
  const left = Math.random() * 100;
  const rotate = Math.random() * 60 - 30;
  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `rotate(${rotate}deg)`,
    fontSize: `${Math.random() * 10 + 12}px`,
    opacity: Math.random() * 0.2 + 0.1,
  };
};
</script>

<style scoped>
.page-wrapper {
  position: relative;
  min-width: 970px;
}

.watermarks {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 10;
}

.watermark {
  position: absolute;
  color: rgba(15, 14, 14, 0.15);
  white-space: nowrap;
  user-select: none;
}

.top-bar {
  padding: 10px 0;
}

.back-btn,
.export-btn {
  margin: 10px;
  padding: 10px 20px;
  font-size: 14px;
  border: none;
  background-color: #00aaff;
  color: white;
  cursor: pointer;
  border-radius: 5px;
}

.export-btn {
  background-color: #4caf50;
}

.export-btn:hover,
.back-btn:hover {
  opacity: 0.8;
}

.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.profile-title {
  text-align: center;
  font-size: 26px;
  font-weight: bold;
  margin: 5px;
}

.profile-header {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.profile-image {
  width: 130px;
  height: 130px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #007bff;
}

.profile-section {
  margin-bottom: 20px;
  background: #f9f9f9;
}

.profile-section h3 {
  font-size: 22px;
  color: #007bff;
  margin-bottom: 10px;
  border-left: 4px solid #007bff;
  padding-left: 10px;
}

.profile-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 8px;
}

.profile-grid p {
  margin: 5px 0;
  line-height: 1.6;
  font-size: 17px;
  color: #333;
}

.table-container {
  overflow-x: auto;
  margin: 20px 0;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.compare-table {
  width: 100%;
  min-width: 800px;
  border-collapse: collapse;
  background: white;
}

.compare-table th {
  background: #f8f9fa;
  font-weight: 600;
  padding: 12px 15px;
  border: 1px solid #ddd;
}

.main-header {
  background: #007bff !important;
  color: white;
  font-size: 16px;
}

.compare-table td {
  padding: 10px 15px;
  border: 1px solid #eee;
  text-align: center;
  min-width: 80px;
}

.summary-row td {
  background: #fff3cd;
  font-weight: bold;
}

.result-cell {
  color: #d35400;
}
</style>